package com.chery.media.utils

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbManager
import com.chery.media.contacts.ActionContacts
import com.chery.media.contacts.EventContacts
import com.chery.media.library.extend.toast
import com.github.mjdev.libaums.UsbMassStorageDevice
import com.github.mjdev.libaums.fs.UsbFile
import com.jeremyliao.liveeventbus.LiveEventBus

/**
 * U盘检测广播
 * https://cloud.tencent.com/developer/article/1743234
 * https://zhuanlan.zhihu.com/p/44973627
 * https://blog.csdn.net/true100/article/details/77775700
 */
class USBBroadcastReceiver: BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        when (intent?.action) {
            ActionContacts.ACTION_USB_PERMISSION -> {
                // U盘权限
                val granted = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)
                if (granted) {
                    // U盘权限获取成功
                    val usbDevice = intent.getParcelableExtra<UsbDevice>(UsbManager.EXTRA_DEVICE)
                    if (usbDevice != null) {
                        // U盘插入
//                        "用户已授权， 可以进行读取操作".toast()
                        LiveEventBus.get<Boolean>(EventContacts.USB_STATUS).post(true)
                    } else {
                        // U盘拔出
//                        "用户已授权， U盘设备不存在".toast()
                        LiveEventBus.get<Boolean>(EventContacts.USB_STATUS).post(false)
                    }
                } else {
                    // U盘权限获取失败
//                    "U盘权限获取失败".toast()
                    LiveEventBus.get<Boolean>(EventContacts.USB_STATUS).post(false)
                }
            }
            UsbManager.ACTION_USB_DEVICE_ATTACHED -> {
                // U盘插入
                val usbDevice = intent.getParcelableExtra<UsbDevice>(UsbManager.EXTRA_DEVICE)
                if (usbDevice != null) {
//                    "U盘已插入， 可以尝试获取设备数据".toast()
                    LiveEventBus.get<Boolean>(EventContacts.USB_STATUS).post(true)
                } else {
//                    "U盘已插入，但设备不存在".toast()
                    LiveEventBus.get<Boolean>(EventContacts.USB_STATUS).post(false)
                }
            }
            UsbManager.ACTION_USB_DEVICE_DETACHED -> {
                // U盘拔出
//                "U盘已拔出".toast()
                LiveEventBus.get<Boolean>(EventContacts.USB_STATUS).post(false)
            }
        }
    }

}